using System.Windows.Forms;
using System.Drawing;
using System.Configuration;
using System.ComponentModel;
using System;

namespace Gl.SettingsManager
{
	internal interface SettingsFormSchema
	{
		[SettingProperty]
		Size FormSize { get; set; }

		[SettingProperty]
		Point FormLocation { get; set; }

		[SettingProperty]
		[WindowStateValidator]
		FormWindowState WindowState { get; set; }
	}

	[SettingsSchema(typeof(SettingsFormSchema))]
	public class SettingsForm : Form, ISettingsContext
	{
		private Size _formSize;
		private Settings _settings;
		private Point _formLocation;

		private Point FormLocation
		{
			get { return _formLocation; }
			set { _formLocation = value; }
		}

		private Size FormSize
		{
			get { return _formSize; }
			set { _formSize = value; }
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			_settings = OnSettingsCreation();
			_settings.Load(this, true);
			OnSettingsLoaded();
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			_settings.Save(this);
			base.OnClosing(e);
		}

		protected virtual Settings OnSettingsCreation()
		{
			return Settings.GetSettingsWithConfigurationFileProvider(
				ConfigurationUserLevel.PerUserRoamingAndLocal);
		}

		protected virtual void OnSettingsLoaded()
		{
			Size = FormSize;
			Location = FormLocation;
		}

		protected override void OnSizeChanged(System.EventArgs e)
		{
			if (Visible && WindowState == FormWindowState.Normal)
				FormSize = Size;
			base.OnSizeChanged(e);
		}

		protected override void OnLocationChanged(EventArgs e)
		{
			if (Visible && WindowState == FormWindowState.Normal)
				FormLocation = Location;
			base.OnLocationChanged(e);
		}

		protected virtual string OnContextNeeded()
		{
			return string.Empty;
		}

		#region ISettingsContext Members

		string ISettingsContext.ContextName
		{
			get { return OnContextNeeded(); }
		}

		#endregion
	}
}
